package com.ityj.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ityj.yygh.oss.service.FileService;
import com.ityj.yygh.oss.utils.ConstantPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.time.LocalDateTime;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Override
    public String uploadFile(MultipartFile multipartFile) {
        // https://help.aliyun.com/document_detail/84781.html 帮助文档
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucket = ConstantPropertiesUtils.BUCKET;

        OSS ossClient = null;
        InputStream inputStream;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            inputStream = multipartFile.getInputStream();
            String uploadFilePath = generateUploadFilePath(multipartFile.getOriginalFilename());
            log.info("UploadFilePath is : {}", uploadFilePath);
            // 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucket, uploadFilePath, inputStream);
            // https://oss-1122test.oss-cn-shanghai.aliyuncs.com/pic1.png
            return "https://" + bucket + endpoint + "/" + uploadFilePath;
        } catch (IOException e) {
            log.error("Error occurs when file upload:", e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    private String generateUploadFilePath(String filename) {
        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int monthValue = now.getMonthValue();
        int dayOfMonth = now.getDayOfMonth();
        String filePath = year + "/" + monthValue + "/" + dayOfMonth + "/";

        String namePrefix = "";
        String nameSuffix = "";
        if (filename.contains(".")) {
            String[] splitStrArr = filename.split("\\.");
            if (splitStrArr.length == 2) {
                namePrefix = splitStrArr[0];
                nameSuffix = splitStrArr[1];
                return filePath + namePrefix + Instant.now().toEpochMilli() + "." + nameSuffix;
            }
        }
        return filePath + Instant.now().toEpochMilli() + filename;
    }
}
